
import React from 'react'
import { connect } from 'react-redux'
import { messages, deepCopy } from 'share/common'
import config from 'config'
import { Form, Button, Table, Select } from 'antd'
const Option = Select.Option;

import RSService from 'containers/setting/role-setting/role-setting.service'
import 'styles/setting/role-setting/finance-role/finance-role-detail.scss'
import ResizeTable from "components/resize-table";

class DetailCostCenter extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      saveLoading: false,
      columns: [],
      originData: [],
      data: [],
      isEdit: false,
      costCenterOptions: [],
      costCenterCodeOptions: [],
    }
  }

  componentDidMount() {
    this.setColumns();
    this.getList()
  }

  getList = () => {
    this.setState({ loading: true });
    RSService.getFinanceCostCenter(this.props.roleOID).then(res => {
      this.setState({ loading: false, data: deepCopy(res.data), originData: deepCopy(res.data) })
    }).catch(() => {
      this.setState({ loading: false })
    })
  };

  setColumns = () => {
    const { isEdit } = this.state;
    let selectorItem = {
      url: '',
      label: record => `${record.code} - ${record.name}`,
      key: 'code',
      searchKey: 'keyword'
    };
    let columns = [
      {title: messages('setting.key903'/*成本中心*/), dataIndex: 'costCenterName', width: '30%', render: (value, record, index) =>
        isEdit ? (
          <Select showSearch
                  style={{width: '100%'}}
                  placeholder={messages('common.please.select')}
                  defaultValue={{key: record.costCenterOID, label: value}}
                  optionFilterProp="children"
                  labelInValue={true}
                  onFocus={this.getCostCenter}
                  onSearch={this.getCostCenter}
                  onChange={result => this.handleChange('cost_center', index, result)}>
            {this.state.costCenterOptions.map(item => {
              return <Option value={item.costCenterOID} key={item.costCenterOID}>{item.name}</Option>
            })}
          </Select>
        ) : value
      },
      {title: messages('setting.key904'/*成本中心值编号从*/), dataIndex: 'costCenterItemCodeFrom', width: '30%',
        render: (value, record, index) => {
        selectorItem.url = `${config.baseUrl}/api/cost/center/${record.costCenterOID}/item/search`;
        return isEdit ? (
          <Select showSearch
                  style={{width: '100%'}}
                  placeholder={messages('common.please.select')}
                  defaultValue={{key: record.costCenterItemCodeFrom, label: value}}
                  allowClear
                  labelInValue={true}
                  disabled={!record.costCenterName}
                  onFocus={inputVal => this.getCostCenterCode(record.costCenterOID, inputVal)}
                  onSearch={inputVal => this.getCostCenterCode(record.costCenterOID, inputVal)}
                  onChange={result => {this.handleChange('costCenterItemCodeFrom', index, result)}}>
            {this.state.costCenterCodeOptions.map(item => {
              return <Option value={item.code} key={item.code}>{item.code} - {item.name}</Option>
            })}
          </Select>
        ) : (value || '-')
      }},
      {title: messages('setting.key905'/*成本中心值编号至*/), dataIndex: 'costCenterItemCodeTo', width: '30%',
        render: (value, record, index) => {
        selectorItem.url = `${config.baseUrl}/api/cost/center/${record.costCenterOID}/item/search`;
        return isEdit ? (
          <Select showSearch
                  style={{width: '100%'}}
                  placeholder={messages('common.please.select')}
                  defaultValue={{key: record.costCenterItemCodeTo, label: value}}
                  allowClear
                  labelInValue={true}
                  disabled={!record.costCenterName}
                  onFocus={inputVal => this.getCostCenterCode(record.costCenterOID, inputVal)}
                  onSearch={inputVal => this.getCostCenterCode(record.costCenterOID, inputVal)}
                  onChange={result => {this.handleChange('costCenterItemCodeTo', index, result)}}>
            {this.state.costCenterCodeOptions.map(item => {
              return <Option value={item.code} key={item.code}>{item.code} - {item.name}</Option>
            })}
          </Select>
        ) : (value || '-')
      }},
      {title: messages('common.operation'), dataIndex: 'costCenterOID', width: '10%', render: value =>
        isEdit ? <a onClick={() => this.handleDelete(value)}>{messages('common.delete')}</a> : '-'}
    ];
    this.setState({ columns })
  };

  //改变编辑状态
  handleEditOrShow = (flag) => {
    !flag && this.setState({ data: deepCopy(this.state.originData) });
    this.setState({ isEdit: flag }, () => {
      this.setColumns()
    })
  };

  //修改成本中心及成本中心值编号
  handleChange = (type, index, value) => {
    let data = this.state.data;
    if (type === 'cost_center') {
      data[index].costCenterName = value.label;
      data[index].costCenterOID = value.key;
      data[index].costCenterItemCodeFrom = '';
      data[index].costCenterItemCodeTo = '';
    } else {
      data[index][type] = value && value.key
    }
    this.setState({ data },() => {
      this.setColumns()
    })
  };

  //删除
  handleDelete = (costCenterOID) => {
    let data = this.state.data;
    data.map((item, index) => {
      if (item.costCenterOID === costCenterOID) {
        data.splice(index, 1)
      }
    });
    this.setState({ data })
  };

  //更新成本中心列表
  handleUpdate = () => {
    this.setState({ loading: true, saveLoading: true });
    let data = [];
    this.state.data.map(obj => {
      Object.keys(obj).length && data.push(obj)
    });
    RSService.updateFinanceCostCenter(this.props.roleOID, data).then(res => {
      if (res.data.success) {
        this.setState({
          loading: false,
          saveLoading: false,
          isEdit: false,
          data,
          originData: deepCopy(data)
        }, () => {
          this.setColumns()
        })
      }
    }).catch(() => {
      this.setState({ loading: false, saveLoading: false })
    })
  };

  //新增一行
  addNewRow = () => {
    let data = this.state.data;
    data.push({});
    this.setState({ data });
  };

  //获取成本中心选择项
  getCostCenter = (value) => {
    RSService.searchCostCenter(value || '', 0, 100).then(res => {
      this.setState({ costCenterOptions: res.data || [] })
    })
  };

  //获取成本中心编码选择项
  getCostCenterCode = (costCenterOID, value) => {
    RSService.searchCostCenterCode(costCenterOID, value || '', 0, 100).then(res => {
      this.setState({ costCenterCodeOptions: res.data || [] })
    })
  };

  render() {
    const { roleBaseInfo } = this.props;
    const { loading, saveLoading, columns, data, isEdit } = this.state;
    return (
      <div className="detail-cost-center">
        {/*系统预设角色不可编辑部门权限*/}
        {roleBaseInfo.roleID !== 'SuperAud' && roleBaseInfo.roleID !== 'SuperFin' && (
          <div className="btns">
            {isEdit ? (
              <div>
                <Button type="primary" loading={saveLoading} onClick={this.handleUpdate}>{messages('common.save')}</Button>
                <Button onClick={() => {this.handleEditOrShow(false)}}>{messages('common.cancel')}</Button>
                <Button onClick={this.addNewRow}>{messages('common.add')}</Button>
              </div>
            ) : <Button type="primary" onClick={() => {this.handleEditOrShow(true)}}>{messages('common.edit')}</Button>}
          </div>
        )}
        <ResizeTable
          rowKey={(record, index) => index}
          columns={columns}
          dataSource={data}
          loading={loading}
          pagination={{pageSize: 1000}}
          size="middle"
          bordered
        />
      </div>
    )
  }
}

DetailCostCenter.propTypes = {
  roleBaseInfo: React.PropTypes.object,
  roleOID: React.PropTypes.string,
};

DetailCostCenter.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
  }
}

const wrappedDetailCostCenter = Form.create()(DetailCostCenter);

export default connect(mapStateToProps)(wrappedDetailCostCenter)
